<template>
  <a-drawer
    :visible="formVisible"
    :width="500"
    :title="isEdit ? '编辑' : '新增'"
    @ok="submit"
    @cancel="close"
  >
    <div>
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col-props="{ span: 8 }"
        :wrapper-col-props="{ span: 16 }"
      >
        <a-form-item field="name" label="名称">
          <a-input v-model="form.name" placeholder="请填写名称" />
        </a-form-item>
        <a-form-item field="type" label="模板类型">
          <a-select
            v-model="form.type"
            allow-clear
            :options="FREIGHT_TYPES"
            placeholder="请选择模板类型"
          />
        </a-form-item>
        <a-form-item v-if="form.type == '0'" field="freight" label="运费">
          <a-input-number
            v-model="form.freight"
            placeholder="请填写运费"
            :min="0"
            allow-clear
            hide-button
          >
            <template #suffix> 元 </template>
          </a-input-number>
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { Message } from '@arco-design/web-vue';
  import { computed, ref } from 'vue';
  import { useVisible } from '@/hooks/visible';
  import {
    addFreightTemplate,
    updateFreightTemplate,
  } from '@/api/mall/freighttemplate';
  import { FREIGHT_TYPES } from '@/api/global';

  const formRef = ref();

  const initData = () => {
    return {
      name: '',
      type: '',
      freight: 0,
    };
  };

  const rules = {
    name: [
      {
        required: true,
        message: '名称不能为空',
      },
    ],
    type: [
      {
        required: true,
        message: '模板类型不能为空',
      },
    ],
  };

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });

  const emit = defineEmits<{
    (e: 'update:visible', v: boolean): void;
    (e: 'refresh'): void;
  }>();

  const form = ref(props.formData);

  const { formVisible, close, open } = useVisible(props, emit);

  // 判断是编辑还是新增
  const isEdit = computed(() => !!form.value.id);

  const submit = async () => {
    formVisible.value = true;
    const validate = await formRef.value.validate();
    if (!validate) {
      if (isEdit.value) {
        await updateFreightTemplate(form.value).then(() => {
          Message.success('修改成功');
        });
      } else {
        await addFreightTemplate(form.value).then(() => {
          Message.success('添加成功');
        });
      }
      form.value = { ...initData };
      formVisible.value = false;
      emit('refresh');
    }
  };

  open(() => {
    const { id } = props.formData;
    if (id) {
      form.value = props.formData;
    } else {
      form.value = initData();
    }
  });
</script>
